package com.example.wxvoce;


import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.documentfile.provider.DocumentFile;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.wxvoce.adapter.MyAdapter;
import com.example.wxvoce.bean.MusicBean;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * 悬浮窗的服务
 *
 * @author an.rustfisher.com
 * @date 2022-01-05 23:53
 */
public class FloatService extends Service {
    private static final String TAG = "rfDevFloatingService";

    private WindowManager windowManager;
    private View floatView;

    private List<ResolveInfo> apps = new ArrayList<>();



    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==0){
                Toast.makeText(getBaseContext(), "替换成功", Toast.LENGTH_SHORT).show();
            }
        }
    };


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        initUi();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void initUi() {
        //悬浮窗
        windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT
        );
        params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.LEFT;


        floatView = new FloatingView(getBaseContext());

        windowManager.addView(floatView, params);

//        这段代码是用户拖动悬浮窗的
        floatView.setOnTouchListener(new View.OnTouchListener() {
            private int initialX;
            private int initialY;
            private float initialTouchX;
            private float initialTouchY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        initialX = params.x;
                        initialY = params.y;
                        initialTouchX = event.getRawX();
                        initialTouchY = event.getRawY();
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        params.x = initialX + (int) (event.getRawX() - initialTouchX);
                        params.y = initialY + (int) (event.getRawY() - initialTouchY);
                        windowManager.updateViewLayout(floatView, params);
                        return true;
                }
                return false;
            }
        });

        //关闭悬浮窗
        ImageView cancel_img = floatView.findViewById(R.id.cancel_float);

        cancel_img.setOnClickListener((view) -> {
            windowManager.removeView(floatView);
        });


        RecyclerView recyclerView = floatView.findViewById(R.id.list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //如果将 orientation 设置为 HORIZONTAL 可以轻易的实现横向的 listview 效果
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        //设置分隔线 （需要时设置）
        recyclerView.addItemDecoration(new DividerItemDecoration(getBaseContext(), DividerItemDecoration.HORIZONTAL));

        List<MusicBean> list = FileUtils.getFileList();

        MyAdapter mAdapter = new MyAdapter(getBaseContext(), list);
        recyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClick(new MyAdapter.OnItemClick() {
            @Override
            public void onClick(int i) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.tencent.mm";
                        DocumentFile documentFile = DocumentFile.fromTreeUri(getBaseContext(), Uri.parse(FileUtils.changeToUri3(path)));
                        DocumentFile doc = FileUtils.getFiles1(documentFile);

                        Uri sourceUri = FileUtils.getFileUri(getBaseContext(),new File(list.get(i).getPath()));
;
               //         Log.v("TGA", doc.getUri().getPath());
                 //       Log.v("TGA", list.get(i).getPath());

                        try {
                            FileUtils.replaceMP3Content(getBaseContext(),sourceUri,doc.getUri());
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }

                        handler.sendEmptyMessage(0);

                    }
                }).start();

            }
        });

    }
}
